<?php

namespace App\Http\Controllers\Seller;

use App\Models\ShopSender;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class SenderController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->assign(['sideMenu' => 'sender']);
    }

    public function index()
    {

        $items = $this->shop->senders;
        return $this->view('seller.sender.index', compact('items'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function newSender(Request $request)
    {
        $id = $request->input('id', 0);
        if ($id) {
            $sender = $this->shop->senders()->find($id);
        } else {
            $sender = new ShopSender();
        }

        return $this->view('seller.sender.newsender', compact('id', 'sender'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function storeSender(Request $request)
    {
        $id = $request->input('id', 0);
        $newsender = Arr::only($request->input('sender', []), [
            'name',
            'phone',
            'province',
            'city',
            'district',
            'town',
            'street',
            'isdefault'
        ]);

        if ($newsender['isdefault']) {
            $this->shop->senders()->update(['isdefault' => 0]);
        }

        if ($id) {
            $sender = $this->shop->senders()->find($id);
            if ($sender) {
                $sender->update($newsender);
            }
        } else {
            $this->shop->senders()->create($newsender);
        }

        return $this->messager()
            ->setMessage(trans('sysmessage.info save success'))
            ->setLinks([
                [trans('common.continue add'), url('seller/sender/newsender')],
                [trans('common.back list'), url('seller/sender')],
            ])->render();
    }

    public function delete(Request $request)
    {
        $id = $request->input('id');
        $this->shop->senders()->where('id', $id)->delete();
        return ajaxReturn();
    }
}
